const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer');
const chalk = require('chalk');
const os = require('os');
const spawn = os.platform() === 'win32' ? require('cross-spawn') : require('child_process').spawn;
const cwd = path.join(__dirname, '..');
const config = require('./.config.json');
const fse = require('fs-extra');
let selects = {
  one: [
    {
      type: 'list',
      name: 'typeSelect',
      message: '请选择打包的类型------------>',
      choices: ['weapp', 'alipay', 'h5', 'tt'],
    },
  ],
  two: [
    {
      type: 'list',
      name: 'envSelect',
      message: '请选择打包的环境------------>',
      choices: Object.keys(config),
    },
  ],
};

//动态更改appid
const changeAppId = async (appId) => {
  await fs.readFile(path.join('./project.config.json'), 'utf8', function (err, data) {
    if (err) throw err;
    let list = JSON.parse(data);
    list.appid = appId;
    let newList = JSON.stringify(list, null, 2);
    fs.writeFile(path.join('./project.config.json'), newList, 'utf8', (err) => {
      if (err) throw err;
      getAppidLog(appId);
    });
  });
};

//动态更改小程序直播插件id
const changeLiveId = async (livePlayerId) => {
  await fs.readFile(path.join('./src/app.config.ts'), 'utf8', function (err, data) {
    if (err) throw err;
    //正则表达式匹配字符串
    let newData = data.replace(/provider: '[a-z,0-9]*'/, `provider: '${livePlayerId}'`)
    fs.writeFile(path.join('./src/app.config.ts'), newData, 'utf8', (err) => {
      if (err) throw err;
      console.log('写入成功')
    });
  });
};

const getEnvLog = (typeSelect, envSelect) => {
  console.log('选择的环境为 ' + chalk.green(typeSelect, envSelect));
};
const getAppidLog = (appidSelect) => {
  console.log('当前打包的appId为：' + chalk.green(appidSelect));
};

const getEnv = () => process.env.TYPE_ENV.includes('prod');

const delImages = () => {
  if (process.env.TARO_ENV !== 'weapp') return;
  const basePath = path.join(__dirname, '..');
  let buildPath = path.join(basePath, '/dist/weapp/assets');
  fse.moveSync(`${buildPath}/image/tab`, `${buildPath}/tab`);
  fse.emptyDirSync(`${buildPath}/image`);
  fse.moveSync(`${buildPath}/tab`, `${buildPath}/image/tab`);
}


(async () => {
  const typeSelect = process.argv[2] || (await inquirer.prompt(selects.one)).typeSelect;
  const envSelect = process.argv[3] || (await inquirer.prompt(selects.two)).envSelect;
  let buildFlag = process.env.TYPE_ENV === 'prod' && !process.env.watch;
  let buildWatchFlag = process.env.watch;
  //编译代码之前替换app.config.ts文件 直播插件id
  // await changeLiveId(config[envSelect]['livePlayerId']);
  //开发环境下默认走的测试appid
  await changeAppId(config[envSelect][typeSelect]);

  process.env.HOST_ENV = envSelect;
  if(config && config[envSelect]) {
    /**
     * 定义环境变量CURRENT_CONFIG
     * 抛出 当前选中的启动环境在.config.json中对应的配置信息
     */
    process.env.CURRENT_CONFIG = JSON.stringify(config[envSelect] || {});
    // 在build、build:watch情况下，替换url
    process.env.OSS_HOST = config[envSelect]['ossHost'];
  }
  let watchFlag = !getEnv() || process.env.watch;
  if (process.env.watch) process.env.NODE_ENV = 'production';
  const ls = spawn('taro', ['build', envSelect, '--type', typeSelect, watchFlag ? '--watch' : '--'], {cwd});

  getEnvLog(typeSelect, envSelect); //输出打包命令

  ls.stdout.pipe(process.stdout); //输出 开始走taro打包

  ls.stderr.on('data', (data) => {
    console.error(`stderr: ${data}`)
  });

  ls.on('close', (code) => {
    if (process.env.TYPE_ENV === 'prod' && typeSelect === 'h5') {
      // 需要外置的config
      const extraConfigKeys = ['rzhost', 'host', 'magicHost', 'renderHost', 'ossHost', 'pvUvHost', 'goldCoinHost'];
      let extraConfig = {};
      extraConfigKeys.forEach(configKey => {
        extraConfig[configKey] = config[process.env.HOST_ENV][configKey];
      });
      extraConfig['hostEnv'] = process.env.HOST_ENV;
      fs.writeFileSync(path.resolve(process.cwd(), 'dist/h5/config.js'), `window.wmConfig = ${JSON.stringify(extraConfig)};`, 'utf-8');
    }
    // build情况下
    console.log('子进程打包结束');
    delImages();
    process.exit(code);
  });
  if (buildWatchFlag) {
    // build:watch情况下，编译结束后删除图片资源
    ls.stdout.on('data', async(msg) => {
      if (`${msg}`.includes('监听文件修改中...')) {
        delImages();
      }
    });
  }
})();
